<template>
  <div class="category">
      <!-- 左边导航 -->
    <div class="left">
      <div class="left_wrapper">
        <Left
          v-for="(item,index) in categoryItems"
          :key="index"
          :item="item"
          :index="index"
          :selectIndex="selectIndex"
          @changeSelectIndex="change"
        />
      </div>
    </div>
    <!-- 右边二级 -->
    <div class="right" ref="right" @touchstart="touchStart">
      <div class="right_wrrapper">
        <div
          v-for="(item,index) in categoryItems"
          :key="index"
          class="right_item"
          ref="block"
        >
          <div class="title">{{item.cname}}</div>
          <div class="right_item_wrapper">
            <Right v-for="(item,index) in item.subcategories" :key="index" :item="item" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import Left from "../components/Left.vue"
import Right from "../components/Right";

export default {
  components: {
    Left,
    Right,
  },
  data() {
    return {
      categoryItems: [],
      selectIndex: 0,
    };
  },
  methods: {
    change(index) {
        // 在切换左边时移除右边的监听滚动的事件
      this.$refs.right.removeEventListener("scroll", this.handleScroll);
      this.selectIndex = index;
      var ss = this.$refs.block;
      console.log(ss);
      var targetBlock = ss[this.selectIndex];
      targetBlock.scrollIntoView({ behavior: "smooth" });
    },
    handleScroll() {
      //获取滚动的距离
      var scrollOffset = event.target.scrollTop;
      console.log(scrollOffset);
      var ss = this.$refs.block;

      for (let index = 0; index < ss.length; index++) {
        if (
          scrollOffset >= ss[index].offsetTop &&
          scrollOffset < ss[index + 1].offsetTop
        ) {
          this.selectIndex = index;
        }
      }
    },
    touchStart() {
      this.$refs.right.addEventListener("scroll", this.handleScroll);
    },
  },
  mounted() {
    axios
      .get("http://api.kudesoft.cn/tdk/category")
      .then((res) => {
        console.log(res);
        this.categoryItems = res.data.data.data;
      })
      .catch(() => {});

    this.$refs.right.addEventListener("scroll", this.handleScroll);
  },
};
</script>

<style scoped>
.category {
  width: 100%;
  height: 100vh;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}

.left {
  height: 100%;
  width: 25%;
  overflow: scroll;
}

.right {
  height: 100%;
  width: 75%;
  overflow: scroll;
}

.right_wrrapper {
  width: 100%;
  display: inline-flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
}

.right_item {
  width: 100%;
  border-bottom: 0.3rem solid red;
}

.right_item_wrapper {
  width: 100%;
  display: inline-flex;
  justify-content: center;
  align-items: flex-start;
  flex-wrap: wrap;
  font-size: 0.5rem;
}

.title {
  height: 1rem;
  font-size: 0.5rem;
}
</style>